import { defineStore } from "pinia";
import { useSysConfig } from "../configs/sys.config";
import { LocalStorage } from "@webxue/common";
import { userTool } from "@/utils/tools/user.tool";
import router from "../router";
import { useConfigStore } from "./config.store";

export const useUserStore = defineStore("userStore", {
  state: () => ({
    // 用户信息
    userInfo: LocalStorage.get(useSysConfig().localKey?.userInfo) || null,
    // 用户token
    userTK: LocalStorage.get(useSysConfig().localKey?.userTK) || null,
    // 用户菜单
    userMenus: LocalStorage.get(useSysConfig().localKey?.userMenus) || [],
  }),
  getters: {
    // 判断是否登录
    isLogin(state) {
      return !!(state.userTK && state.userInfo);
    },
    // 成功拥有开发者权限
    isDeveloperSucc(state){
      return state.userInfo?.developerId && state.userInfo?.developerStatus === 1;
    },
    // 判断当前用户是否是超管
    isSuperAdmin(state){
      return userTool.isSuperAdmin(state.userInfo?.roleCodes);
    },
    // 判断当前用户是否是客服
    isCusSer(state){
      return userTool.isCusSer(state.userInfo?.roleCodes);
    },
    // 判断用户有没有指定权限
    hasPermission(state) {
      return (permissionCode:string) => state.userInfo.permissionCodes?.split(",")?.includes(permissionCode);
    }
  },
  actions: {
    // 设置用户信息
    setUserInfo(userInfo: Record<string, any> | null) {
      this.userInfo = userInfo;
      LocalStorage.set(useSysConfig().localKey?.userInfo, this.userInfo);
    },
    // 设置用户token
    setUserTK(userTK: Record<string, any> | null) {
      this.userTK = userTK;
      LocalStorage.set(useSysConfig().localKey?.userTK, this.userTK);
    },
    // 设置用户菜单
    setUserMenus(userMenus: Record<string, any> | null) {
      this.userMenus = userMenus;
      LocalStorage.set(useSysConfig().localKey?.userMenus, this.userMenus);
    },

    // 移除用户信息
    removeUserInfo() {
      this.userInfo = null;
      LocalStorage.remove(useSysConfig().localKey?.userInfo);
    },
    // 移除用户token
    removeUserTK() {
      this.userTK = null;
      LocalStorage.remove(useSysConfig().localKey?.userTK);
    },
    // 移除用户token
    removeUserMenus() {
      this.userMenus = [];
      LocalStorage.remove(useSysConfig().localKey?.userMenus);
    },
    // 退出登录
    async logout() {
      this.removeUserInfo();
      this.removeUserTK();
      this.removeUserMenus();
      useConfigStore().removeConfigJson();
      await router.replace(`/sys/login?_redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`);
    }
  }
});
